package com.heima.comment.service.Imp;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    //mongo依赖
    @Autowired
    private MongoTemplate mongoTemplate;
    //远程调用
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private CommentHotService commentHotService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //1.校验参数
        //校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "当前未登录，请先登录!");
        }
        //校验文章id 不为空 校验内容的长度不能大于140个字符(validated校验)
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章id不能为空!");
        }
        //2.阿里云校验评论内容是否违规
        String needContent = AginstOrNot(dto);
        //3.远程查询当前登录用户信息
        ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
        //对远程调用做判断
        if (!responseResult.checkCode()) {
            log.info("远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        //获取其中的用户数据
        ApUser apUser = responseResult.getData();
        //4.创建评论信息，并保存到mongo
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short)0);
        if (needContent == null) {
            needContent = dto.getContent();
        }
        apComment.setContent(needContent);
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short)0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.insert(apComment);
        //===========================================
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setAdd(1);
        mess.setArticleId(dto.getArticleId());
        mess.setType(NewBehaviorDTO.BehaviorType.COMMENT);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE,JSON.toJSONString(mess));
        log.info("评论行为 发送消息=={}", JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }

    /**
     * 阿里云检测 获得过滤后的文章内容
     *
     * @param dto
     */
    public String AginstOrNot(CommentSaveDTO dto) {
        String content = dto.getContent();
        if (StringUtils.isEmpty(content)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不能为空!");
        }
        try {
            ScanResult result = greenScan.greenTextScan(content);
            //过滤掉的词汇：替换为**
            content = result.getFilteredContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 点赞评论
     * @param dto
     * @return
     */
    //解决线程安全问题
    @Autowired
    private RedissonClient redisson;
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //创建分布式线程安全锁
        RLock lock = redisson.getLock("mylock");
        //上锁
        lock.lock();
        //0.准备参数封装容器
        HashMap<String, Integer> map = new HashMap<>();
        try {
            //1. 参数校验
            //   评论id不能为空  operation必须为 0  或  1
            Short operation = dto.getOperation();
            if (operation != 0 && operation != 1) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"传递的操作参数错误!");
            }
            //2. 根据评论id查询评论数据， 为null返回错误信息
            Query apCommentQuery = Query.query(Criteria.where("id").is(dto.getCommentId()));
            ApComment apComment = mongoTemplate.findOne(apCommentQuery, ApComment.class);
            if (apComment == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询结果不存在!");
            }
            //获取点赞的用户id
            ApUser user = AppThreadLocalUtils.getUser();
            //3. 如果是点赞操作 判断是否已经点赞
            //查询是否点赞   用户id和评论的id结合查询
            Query apCommentLikeQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
            ApCommentLike commentLike = mongoTemplate.findOne(apCommentLikeQuery, ApCommentLike.class);
            if (operation == 0) {
                //   点过赞提示 请勿重复点赞
                if (commentLike == null) {
                    //   未点过赞   保存点赞信息到mongo
                    ApCommentLike apCommentLike = new ApCommentLike();
                    //当前评论者的id
                    apCommentLike.setAuthorId(user.getId());
                    apCommentLike.setCommentId(dto.getCommentId());
                    apCommentLike.setOperation(dto.getOperation());
                    mongoTemplate.insert(apCommentLike);
                    //   并修改评论信息的点赞数量( + 1)
                    Update apCommentUpdate = new Update();
                    apCommentUpdate.set("likes",apComment.getLikes() + 1)
                            .set("updatedTime",new Date());
                    //更新保存的评论集合
                    mongoTemplate.updateMulti(apCommentQuery,apCommentUpdate,ApComment.class);
                    //查询最新数据
                    ApComment curApcomment = mongoTemplate.findOne(apCommentQuery, ApComment.class);
                    //进行热点计算
                    commentHotService.hotCommentExecutor(curApcomment);
                    map.put("likes",curApcomment.getLikes());
                } else {
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
                }
            } else {
                //4. 如果是取消点赞操作
                //   删除点赞信息
                mongoTemplate.remove(apCommentLikeQuery,ApCommentLike.class);

                //  并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                Update apCommentUpdate = new Update();
                apCommentUpdate.set("likes",apComment.getLikes() - 1)
                        .set("updatedTime",new Date());
                //更新保存的评论集合
                mongoTemplate.updateMulti(apCommentQuery,apCommentUpdate,ApComment.class);
                ApComment curApcomment = mongoTemplate.findOne(apCommentQuery, ApComment.class);
                map.put("likes",curApcomment.getLikes());
            }
        } finally {//解除分布式线程安全锁
            lock.unlock();;

        }
        //1. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        return ResponseResult.okResult(map);
    }

    /**
     * 评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        ResponseResult result = new ResponseResult<>();
        //1. 参数校验
        //   校验文章id  Validated校验 校验size  Validated校验
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }

        //1. 根据条件查询评论列表
        // ========================需要变更处 start =============================
        //   (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
        List<ApComment> apComments = null ;

        if (dto.getIndex() == 1) { // 判断当前是否是第一页评论;
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query hotCommentQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                            .and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes")).limit(dto.getSize());//dto.getMinDate()
            apComments = mongoTemplate.find(hotCommentQuery, ApComment.class);
            // 新size = size - 热评数量
            Integer newSize = dto.getSize() - apComments.size();
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query apCommentQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                            .and("flag").is(0).and("createdTime").lt(dto.getMinDate()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(newSize);//dto.getMinDate()
            List<ApComment> commonComment = mongoTemplate.find(apCommentQuery, ApComment.class);
            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            apComments.addAll(commonComment);
        } else {
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
            Query apCommentQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                            .and("flag").is(0).and("createdTime").lt(dto.getMinDate()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(dto.getSize());//dto.getMinDate()
           apComments = mongoTemplate.find(apCommentQuery, ApComment.class);
        }
        //// ========================需要变更处 end =============================

        return loginOrNotQueryComment(apComments);
    }

   public ResponseResult loginOrNotQueryComment(List<ApComment>  apComments){
       ResponseResult<Object> result = new ResponseResult<>();
       //2. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //3. 如果未登录直接返回评论列表
            result = ResponseResult.okResult(apComments);
        }else {

            //4. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
            //   (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
            List<String> idList = apComments.stream().map(ApComment::getId).collect(Collectors.toList());
            //当前用户的点赞列表
            List<ApCommentLike> commentLikeList = mongoTemplate.find(
                    Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId())
                    ), ApCommentLike.class);
            //   推荐实现:
            //   5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //                 commentId  in    评论id列表   authorId = 登录人id
            //评论列表 点赞列表都不为空
            if (CollectionUtils.isNotEmpty(apComments) ) {
                //获取当前用户点赞评论的id
                List<String> commentIds = commentLikeList.stream().map(ApCommentLike::getCommentId).collect(Collectors.toList());
                result = ResponseResult.okResult(apComments.stream().map(comment -> parseCommentVo(comment,commentIds)));
            }
        }
       return result;
    }

    /**
     * 封装点赞的opention
     * @param comment
     * @param commentIds
     * @return
     */
    public ApCommentVo parseCommentVo(ApComment comment,List<String> commentIds){
        ApCommentVo apCommentVo = new ApCommentVo();
        BeanUtils.copyProperties(comment,apCommentVo);
        //遍历用户点赞列表
        if (commentIds.contains(comment.getId())) {
            apCommentVo.setOperation((short)0);
        }
        return apCommentVo;
    }
}
